package com.ma.cardgame

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.gridlayout.widget.GridLayout
import android.widget.TextView
import android.widget.LinearLayout
import android.widget.ScrollView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.ma.cardgame.model.model.CardMatchingGame

class MainActivity : AppCompatActivity(),View.OnClickListener{
    lateinit var game: CardMatchingGame

    val cardButtons = mutableListOf<Button>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)

        for (v in gridLayout.children){
            if(v is Button){
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        // 确保有足够的按钮
        if (cardButtons.isNotEmpty()) {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }

        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            if (cardButtons.isNotEmpty()) {
                game = CardMatchingGame(cardButtons.count())
                updateUI()
            }
        }

        // 返回到封面页（SecondActivity）
        val back = findViewById<Button>(R.id.button_back)
        back.setOnClickListener {
            finish()
        }

        // 设置可折叠规则区域
        setupCollapsibleRules()
    }

    private fun setupCollapsibleRules() {
        val rulesHeader = findViewById<LinearLayout>(R.id.rules_header)
        val rulesContentScroll = findViewById<ScrollView>(R.id.rules_content_scroll)
        val rulesArrow = findViewById<TextView>(R.id.rules_arrow)
        
        var isExpanded = false
        
        rulesHeader.setOnClickListener {
            isExpanded = !isExpanded
            if (isExpanded) {
                rulesContentScroll.visibility = View.VISIBLE
                rulesArrow.text = "▲"
            } else {
                rulesContentScroll.visibility = View.GONE
                rulesArrow.text = "▼"
            }
        }
    }
    @SuppressLint("DefaultLocale")
    fun updateUI(){
        if (cardButtons.isEmpty() || !::game.isInitialized) return

        for (button in cardButtons){
            val index = cardButtons.indexOf(button)
            if (index < game.cards.size) {
                val card = game.cardAtIndex(index)
                button.isEnabled = !card.isMatched
                if(card.isChosen){
                    button.text = card.toString()
                    button.setBackgroundColor(Color.WHITE)
                }else{
                    button.text = ""
                    button.setBackgroundResource(R.drawable.card)
                }
            }
        }
        val score = findViewById<TextView>(R.id.textView)
        score.text = String.format("%s%d",getString(R.string.score),game.score)

        // 将分数写入 SharedPreferences，供 SecondActivity 显示
        getSharedPreferences("profile", MODE_PRIVATE)
            .edit()
            .putInt("score", game.score)
            .apply()
    }

    override fun onClick(v: View?) {
        if(v is Button && ::game.isInitialized){
            val index = cardButtons.indexOf(v)
            if (index >= 0 && index < game.cards.size) {
                game.chooseCardAtIndex(index)
                updateUI()
            }
        }
    }
}
